package net.pws.oos.web;

import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.WebRequest;

public class CustomWebBindingInitializer implements WebBindingInitializer {
    
    public static final SimpleDateFormat shortDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    
    public static final SimpleDateFormat longDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    public void initBinder(WebDataBinder binder, WebRequest request) {
        shortDateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class,
                                    new CmsDateEditor(shortDateFormat,
                                                      longDateFormat,
                                                      true));
    }
    
    public static class CmsDateEditor extends PropertyEditorSupport {
        
        private final DateFormat shortDateFormat;
        
        private final DateFormat longDateFormat;
        
        private final boolean allowEmpty;
        
        public CmsDateEditor(DateFormat shortDateFormat,
                             DateFormat longDateFormat,
                             boolean allowEmpty) {
            this.shortDateFormat = shortDateFormat;
            this.longDateFormat = longDateFormat;
            this.allowEmpty = allowEmpty;
        }
        
        public String getAsText() {
            Date value = (Date) getValue();
            return (value != null ? this.longDateFormat.format(value) : "");
        }
        
        public void setAsText(String text) throws IllegalArgumentException {
            if (this.allowEmpty && !StringUtils.hasText(text)) {
                // Treat empty String as null value.
                setValue(null);
            }
            else {
                try {
                    setValue(this.longDateFormat.parse(text));
                }
                catch (ParseException ex) {
                    try {
                        setValue(this.shortDateFormat.parse(text));
                    }
                    catch (ParseException ex1) {
                        IllegalArgumentException iae = new IllegalArgumentException("Could not parse date: " + ex1.getMessage());
                        iae.initCause(ex1);
                        throw iae;
                    }
                }
            }
        }
        
    }
    
}
